package com.wzdigit.wms.wms.service.core.inventory;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wzdigit.wms.basic.client.Pager;
import com.wzdigit.wms.basic.client.PagerInfo;
import com.wzdigit.wms.basic.client.request.report.OrderBlotterReportSearchRequest;
import com.wzdigit.wms.basic.client.response.report.OrderBlotterReportReponse;
import com.wzdigit.wms.basic.enums.*;
import com.wzdigit.wms.basic.mapper.core.inventory.OrderBlotterReportMapper;
import com.wzdigit.wms.common.entity.ExcelExportConfig;
import com.wzdigit.wms.common.utils.HttpExcel;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *  订单流水报表Service
 * Created by zyf on 2021/5/12 19:23
 */
@Service
@Slf4j
public class OrderBlotterReportService {

    @Autowired
    private OrderBlotterReportMapper orderBlotterReportMapper;

    //去除空格
    private void filterSpace(OrderBlotterReportSearchRequest search){
        if (search.getFilter()!=null){
            search.setFilter(search.getFilter().replace(" ",""));
        }
        if (search.getFilter2()!=null){
            search.setFilter2(search.getFilter2().replace(" ",""));
        }
        if (search.getSoNo()!=null){
            search.setSoNo(search.getSoNo().replace(" ",""));
        }
        if (search.getPoNo()!=null){
            search.setPoNo(search.getPoNo().replace(" ",""));
        }
        if (search.getBillNo()!=null){
            search.setBillNo(search.getBillNo().replace(" ",""));
        }
    }

    //查询订单流水报表【复用】
    public List<OrderBlotterReportReponse> selectOrderBlotter(OrderBlotterReportSearchRequest search){
        if (search.getWhsType()==null){
            search.setWhsType(3);
        }
        //根据前端传的long毫秒值设置时间
        if (search.getBeginTime()!=null){
            search.setBeginTimeDate(new Date(search.getBeginTime()));
        }
        if (search.getEndTime()!=null){
            search.setEndTimeDate(new Date(search.getEndTime()));
        }
        if (search.getCloseBeginTime()!=null){
            search.setCloseBeginTimeDate(new Date(search.getCloseBeginTime()));
        }
        if (search.getCloseEndTime()!=null){
            search.setCloseEndTimeDate(new Date(search.getCloseEndTime()));
        }

        //查询字段去除空格
        this.filterSpace(search);

        if (search.getWhsType().equals(1)){
            search.setFilter2(search.getFilter());
            search.setFilter(null);
        }

        List<OrderBlotterReportReponse> results = orderBlotterReportMapper.selectAll(search);

        //设置单据状态和单据类型
        for (OrderBlotterReportReponse result : results) {
            if (result.getFlag().equals("ASN")){
                AsnTypeEnum asnTypeEnum = AsnTypeEnum.getEnumByCode(result.getBillType());
                AsnDtlStatusEnum asnDtlStatusEnum = AsnDtlStatusEnum.getEnumByCode(result.getBillStatus());
                if (asnTypeEnum!=null){
                    result.setRetrunBillType(asnTypeEnum.enumName);
                }
                if (asnDtlStatusEnum!=null){
                    result.setRetrunBillStatus(asnDtlStatusEnum.enumName);
                }
            }else if(result.getFlag().equals("GDN")){
                GdnTypeEnum gdnTypeEnum = GdnTypeEnum.getEnumByCode(result.getBillType());
                if (gdnTypeEnum!=null){
                    result.setRetrunBillType(gdnTypeEnum.enumName);
                }
                GdnDtlStatusEnum gdnDtlStatusEnum = GdnDtlStatusEnum.getEnumByCode(result.getBillStatus());
                if (gdnDtlStatusEnum!=null){
                    result.setRetrunBillStatus(gdnDtlStatusEnum.enumName);
                }
                if (search.getWhsType().equals(1)){
                    if (result.getBillStatus().equals(GdnDtlStatusEnum.SHIPMENTED.code)){
                        result.setRetrunBillStatus("完成");
                    }
                }
            }else {
                if (result.getBillType().equals(TransferTypeEnum.T05.code)){
                    result.setRetrunBillType(TransferTypeEnum.T05.enumName);
                    result.setRcvQty(0);
                }else if (result.getBillType().equals(TransferTypeEnum.T06.code)){
                    result.setRetrunBillType(TransferTypeEnum.T06.enumName);
                    result.setShipQty(0);
                }else {
                    TransferTypeEnum transferTypeEnum = TransferTypeEnum.getEnumByCode(result.getBillType());
                    if (transferTypeEnum!=null){
                        result.setRetrunBillType(transferTypeEnum.enumName);
                    }
                }
                TransferDtlStatusEnum transferDtlStatusEnum = TransferDtlStatusEnum.getEnumByCode(result.getBillStatus());
                if (transferDtlStatusEnum!=null){
                    result.setRetrunBillStatus(transferDtlStatusEnum.enumName);
                }
            }
        }
        return results;
    }

    //分页查询订单流水报表
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public PagerInfo<List<OrderBlotterReportReponse>> searchOrderBlotReport(
            OrderBlotterReportSearchRequest search, Pager<?> pager){
        Page<OrderBlotterReportReponse> page = PageHelper.offsetPage(pager.getSkipCount(), pager.getMaxResultCount());
        List<OrderBlotterReportReponse> datas = this.selectOrderBlotter(search);
        PagerInfo<List<OrderBlotterReportReponse>> pagerInfo = new PagerInfo<>();
        pagerInfo.setTotalCount(page.getTotal());
        Integer count;
        Integer allCount;
        for (OrderBlotterReportReponse data : datas) {
            allCount= orderBlotterReportMapper.selectAllPostBackCount(data.getBillNo());
            count= orderBlotterReportMapper.selectPostBackCount(data.getBillNo());
            if (allCount.equals(0)){
                continue;
            }
            if (count.equals(allCount)){
                data.setPostResult("回传成功");
            }else {
                data.setPostResult("回传失败");
            }
        }

        pagerInfo.setItems(datas);

        return pagerInfo;
    }

    //导出订单流水报表信息
    @Transactional
    public void exportOrderBlotReport(
            OrderBlotterReportSearchRequest search,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        ServletOutputStream out = null;
        XSSFWorkbook workbook = null;
        try {
            long time1 = new Date().getTime();
            List<OrderBlotterReportReponse> resultDatas = this.selectOrderBlotter(search);
            long time2 = new Date().getTime();
            System.out.println("查询主数据耗时======》"+(time2-time1));
            Integer count;
            Integer allCount;
            for (OrderBlotterReportReponse data : resultDatas) {
                allCount= orderBlotterReportMapper.selectAllPostBackCount(data.getBillNo());

                if (allCount.equals(0)){
                    continue;
                }
                count= orderBlotterReportMapper.selectPostBackCount(data.getBillNo());

                if (count.equals(allCount)){
                    data.setPostResult("回传成功");
                }else {
                    data.setPostResult("回传失败");
                }
            }
            long time3 = new Date().getTime();
            System.out.println("查询回传结果耗时======》"+(time3-time2));
            List<ExcelExportConfig> configs = new ArrayList<>();
            configs.add(new ExcelExportConfig("单据号", "billNo", 120));
            configs.add(new ExcelExportConfig("数据回传", "postResult", 120));
            configs.add(new ExcelExportConfig("单据日期", "createTime", 120));
            configs.add(new ExcelExportConfig("转出组织", "fmFactory", 120));
            configs.add(new ExcelExportConfig("转入组织", "toFactory", 120));
            configs.add(new ExcelExportConfig("审核日期", "approvedTime", 120));
            configs.add(new ExcelExportConfig("结束本次时间", "closeEndTime", 120));
            configs.add(new ExcelExportConfig("转出仓库编码", "fmWhsCode", 120));
            configs.add(new ExcelExportConfig("转出仓库名称", "fmWhsName", 120));
            configs.add(new ExcelExportConfig("转入仓库编码", "toWhsCode", 120));
            configs.add(new ExcelExportConfig("转入仓库名称", "toWhsName", 120));
            configs.add(new ExcelExportConfig("转出订单号", "fmPoNo", 120));
            configs.add(new ExcelExportConfig("转入订单号", "toPoNo", 120));
            configs.add(new ExcelExportConfig("转出销售订单", "fmSoNo", 120));
            configs.add(new ExcelExportConfig("转出销售订单行号", "fmSoNoLine", 120));
            configs.add(new ExcelExportConfig("转入销售订单", "toSoNO", 120));
            configs.add(new ExcelExportConfig("转入销售订单行号", "toSoNOLine", 120));
            configs.add(new ExcelExportConfig("物料代码", "skuCode", 120));
            configs.add(new ExcelExportConfig("物料描述", "descCn", 120));
            configs.add(new ExcelExportConfig("入库数量", "rcvQty", 120));
            configs.add(new ExcelExportConfig("出库数量", "shipQty", 120));
            configs.add(new ExcelExportConfig("单据类型", "retrunBillType", 120));
            configs.add(new ExcelExportConfig("单据状态", "retrunBillStatus", 120));
            workbook = HttpExcel.newListToExcel(resultDatas, configs);
            String userAgent = servletRequest.getHeader("USER-AGENT");
            String fileName = "订单流水报表";
            if (userAgent.contains("Mozilla")) {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "utf8");
            }
            servletResponse.setContentType("application/octet-stream");
            servletResponse.setHeader("Content-Disposition", "attachment;fileName=" + fileName + ".xlsx");
            servletResponse.flushBuffer();
            out = servletResponse.getOutputStream();
            workbook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
            if(workbook != null) {
                workbook.close();
            }
        }

    }


}
